import { PrismaClient } from "@prisma/client";
import { NotificationType } from "../constants/notificationType";
import { mqttClient } from "../config/mqtt";

const prisma = new PrismaClient();

/**
 * 统一发送通知（插入 DB + MQTT 推送）
 */
export const sendNotification = async ({
  to,
  type,
  content,
  data,
}: {
  to: number; // 接收者
  type: NotificationType;
  content: string;
  data?: Record<string, any>;
}) => {
  const notification = await prisma.notifications.create({
    data: {
      user_id: to,
      type,
      content,
      status: 0
    },
  });

  // MQTT 推送到 chat/notice/{user_id}
  mqttClient.publish(
    `chat/notice/${to}`,
    JSON.stringify({
      id: notification.id,
      type,
      content,
      created_at: notification.created_at,
      read: false,
    })
  );

  return notification;
};


